<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/sj-request'

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 班级列表数据
const classesList = ref([])

// 搜索关键词
const keyword = ref('')

// 加载状态
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加班级')
const formData = ref({
  id: null,
  name: ''
})
const formRules = {
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}
const formRef = ref(null)

// 获取班级列表数据
const getClassesList = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/classes/page',
      method: 'get',
      params: {
        page: currentPage.value,
        size: pageSize.value,
        keyword: keyword.value
      }
    })
    if (res.code === 200) {
      classesList.value = res.data.records.map((item, index) => ({
        ...item,
        order: index + 1
      }))
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取班级列表失败')
    }
  } catch (error) {
    console.error('获取班级列表出错:', error)
    ElMessage.error('获取班级列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getClassesList()
}

// 处理每页显示条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getClassesList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getClassesList()
}

// 重置表单
const resetForm = () => {
  formData.value = {
    id: null,
    name: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 打开添加班级对话框
const handleAdd = () => {
  dialogTitle.value = '添加班级'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑班级对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑班级'
  formData.value = {
    id: row.id,
    name: row.name
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const isEdit = formData.value.id !== null
        const url = isEdit ? '/classes' : '/classes'
        const method = isEdit ? 'put' : 'post'
        
        const res = await request({
          url,
          method,
          data: formData.value
        })
        
        if (res.code === 200) {
          ElMessage.success(isEdit ? '编辑班级成功' : '添加班级成功')
          dialogVisible.value = false
          getClassesList()
        } else {
          ElMessage.error(res.message || (isEdit ? '编辑班级失败' : '添加班级失败'))
        }
      } catch (error) {
        console.error(isEdit ? '编辑班级出错:' : '添加班级出错:', error)
        ElMessage.error(isEdit ? '编辑班级失败' : '添加班级失败')
      }
    }
  })
}

// 处理删除班级
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除班级 "${row.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await request({
        url: `/classes/${row.id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除班级成功')
        // 如果当前页只有一条数据且不是第一页，则删除后跳转到上一页
        if (classesList.value.length === 1 && currentPage.value > 1) {
          currentPage.value--
        }
        getClassesList()
      } else {
        ElMessage.error(res.message || '删除班级失败')
      }
    } catch (error) {
      console.error('删除班级出错:', error)
      ElMessage.error('删除班级失败')
    }
  }).catch(() => {
    // 取消删除操作
  })
}

// 页面加载时获取数据
onMounted(() => {
  getClassesList()
})
</script>

<template>
  <div class="classes-container">
    <div class="classes-header">
      <span>班级列表</span>
      <div class="classes-actions">
        <el-input
          v-model="keyword"
          placeholder="请输入班级名称搜索"
          clearable
          @keyup.enter="handleSearch"
          style="width: 250px; margin-right: 10px;"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 添加班级
        </el-button>
      </div>
    </div>
    
    <el-table
      :data="classesList"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="order" label="序号" width="80" />
      <el-table-column prop="name" label="班级名称" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button link type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>
    
    <!-- 添加/编辑班级对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @closed="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入班级名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.classes-container {
  padding: 20px;
}

.classes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.classes-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>